#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
查询fund_info表的脚本
功能：
1. 查看表结构
2. 查询最新的一条记录
"""

import os
import sys
import django
from django.db import connection

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wealth_backend.settings')
django.setup()

from data_service.models import FundInfo

def show_table_structure():
    """
    显示fund_info表的结构
    """
    print("=" * 50)
    print("fund_info表结构：")
    print("=" * 50)
    
    with connection.cursor() as cursor:
        cursor.execute("DESCRIBE fund_info")
        columns = cursor.fetchall()
        
        print(f"{'字段名':<20} {'类型':<20} {'是否为空':<10} {'键':<10} {'默认值':<15} {'额外':<15}")
        print("-" * 100)
        
        for column in columns:
            field, type_info, null, key, default, extra = column
            print(f"{field:<20} {type_info:<20} {null:<10} {key:<10} {str(default):<15} {extra:<15}")
    
    print()

def show_latest_record():
    """
    显示最新的一条记录
    """
    print("=" * 50)
    print("fund_info表最新记录：")
    print("=" * 50)
    
    try:
        # 获取最新的一条记录
        latest_fund = FundInfo.objects.latest('id')
        
        print(f"ID: {latest_fund.id}")
        print(f"基金代码: {latest_fund.fund_code}")
        print(f"基金名称: {latest_fund.fund_name}")
        print(f"基金类型: {latest_fund.fund_type}")
        print(f"基金公司: {latest_fund.fund_company}")
        print(f"成立日期: {latest_fund.establishment_date}")
        print(f"基金经理: {latest_fund.fund_manager}")
        print(f"基金规模: {latest_fund.fund_size}")
        print(f"管理费率: {latest_fund.management_fee}")
        print(f"托管费率: {latest_fund.custodian_fee}")
        print(f"风险等级: {latest_fund.risk_level}")
        print(f"投资目标: {latest_fund.investment_objective}")
        print(f"投资范围: {latest_fund.investment_scope}")
        print(f"业绩比较基准: {latest_fund.benchmark}")
        print(f"状态: {latest_fund.status}")
        print(f"数据源: {latest_fund.data_source}")
        print(f"创建时间: {latest_fund.created_at}")
        print(f"更新时间: {latest_fund.updated_at}")
        
    except FundInfo.DoesNotExist:
        print("表中暂无数据")
    except Exception as e:
        print(f"查询出错: {e}")
    
    print()

def show_record_count():
    """
    显示记录总数
    """
    try:
        count = FundInfo.objects.count()
        print(f"fund_info表总记录数: {count}")
        print()
    except Exception as e:
        print(f"查询记录数出错: {e}")

def main():
    """
    主函数
    """
    print("fund_info表查询工具")
    print("=" * 50)
    
    # 显示记录总数
    show_record_count()
    
    # 显示表结构
    show_table_structure()
    
    # 显示最新记录
    show_latest_record()

if __name__ == '__main__':
    main()